﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoreEPG.Model;
using System.Windows.Threading;
using System.Diagnostics;
using Microsoft.Win32;
using System.IO;
using MoreEPG.Helper;
using System.Collections;

namespace MoreEPG.Data
{
    public class ClickFinderData : IData
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private string Logo_Path;
        private string GuideImage_Path;
        private string ClickfinderUpdater;
        private string output_Path = HelperClass.appStartPath + @"\tmp\";
        private string TvdatenXmlFile = HelperClass.appStartPath + @"\tmp\tvdaten.xml";
        private string SenderXML_Path = HelperClass.appStartPath + @"\Conf\";
        private string Sender_Conf;
        
        private tvdatenDataSet ds;
        private SenderDataset senderXML;

        #region Constructor

        public ClickFinderData()
        {
            this.setVars();
            this.ds = new tvdatenDataSet();
        }

        #endregion

        #region IData Member

        private string _DBPath = null;
        public string DBPath
        {
            get
            {
                if (this._DBPath == null)
                {
                    this._DBPath = this.GetDBPath();
                }
                return this._DBPath;
            }
            set
            {
                this._DBPath = value;
            }
        }

        private ResultCollections _results = new ResultCollections();
        public ResultCollections Results
        {
            get
            {
                if (!_results.isValid)
                {
                    _results.Images = this._Images;
                    _results.KeyWords = this._KeyWords;
                    _results.Persons = this._Persons;
                    _results.TVChannels = this._TVChannels;
                    _results.TVprograms = this._TVprograms;
                }
                return _results;
            }
        }

        private GuideImageCollection _Images;
        public GuideImageCollection Images
        {
            get
            {
                if (this._Images == null)
                     this._Images = new GuideImageCollection();
                return this._Images;
            }
            set
            {
                this._Images = value;
            }
        }

        private KeywordCollection _KeyWords;
        public KeywordCollection KeyWords
        {
            get
            {
                if (this._KeyWords == null)
                    this._KeyWords = new KeywordCollection();
                return this._KeyWords;
                 
            }
            set
            {
                this._KeyWords = value;
            }
        }

        private PersonCollection _Persons;
        public PersonCollection Persons
        {
            get
            {
                if (this._Persons == null)
                    this._Persons = new PersonCollection();
                return this._Persons;
            }
            set
            {
                this._Persons = value;
            }
        }

        private TVChannelCollection _TVChannels;
        public TVChannelCollection TVChannels
        {
            get
            {
                if (this._TVChannels == null)
                    this._TVChannels = new TVChannelCollection();
                return this._TVChannels;
            }
            set
            {
                this._TVChannels = value;
            }
        }

        private TVProgrammeCollection _TVprograms;
        public TVProgrammeCollection TVprograms
        {
            get
            {
                if (this._TVprograms == null)
                    this._TVprograms = new TVProgrammeCollection();
                return this._TVprograms;
            }
            set
            {
                this._TVprograms = value;
            }
        }

        private Dispatcher _UiDispatcher;
        public Dispatcher UiDispatcher
        {
            get
            {
                return this._UiDispatcher;
            }
            set
            {
                this._UiDispatcher = value;
            }
        }

        private Delegate _ProgressDelegate;
        public Delegate ProgressDelegate
        {
            get
            {
                return this._ProgressDelegate;
            }
            set
            {
                this._ProgressDelegate = value;
            }
        }

        private MCChannelInfoCollection _MCChannelInfos;
        public MCChannelInfoCollection MCChannelInfos
        {
            get
            {
                if (this._MCChannelInfos == null)
                    this._MCChannelInfos = new MCChannelInfoCollection();
                return this._MCChannelInfos;
            }
            set
            {
                this._MCChannelInfos = value;
            }
        }

        private MCImageInfoCollection _MCImages;
        public MCImageInfoCollection MCImages
        {
            get
            {
                if (this._MCImages == null)
                    this._MCImages = new MCImageInfoCollection();
                return this._MCImages;
            }
            set
            {
                this._MCImages = value;
            }
        }

        private MCPersonInfoCollection _MCPersons;
        public MCPersonInfoCollection MCPersons
        {
            get
            {
                if (this._MCPersons == null)
                    this._MCPersons = new MCPersonInfoCollection();
                return this._MCPersons;
            }
            set
            {
                this._MCPersons = value;
            }
        }

        private MCProgramInfoCollection _MCPrograms;
        public MCProgramInfoCollection MCPrograms
        {
            get
            {
                if (this._MCPrograms == null)
                    this._MCPrograms = new MCProgramInfoCollection();
                return this._MCPrograms;
            }
            set
            {
                this._MCPrograms = value;
            }
        }

        public bool UpdateSource()
        {
            updateClickfinderDB();
            return true;
        }

        public TVChannelCollection GetTVChannelCollectionOnly()
        {
            ConvertMDB(true);
            FillSenderCollection(true);
            return this.TVChannels;
        }

        public bool FillDataSet()
        {
            ConvertMDB(false);
            this.UiDispatcher.BeginInvoke(this.ProgressDelegate, 50, 0, -1);
            this.ds.ReadXml(this.TvdatenXmlFile);
            this.UiDispatcher.BeginInvoke(this.ProgressDelegate, 100, 0, -1);
            return true;
        }

        public bool FillCollections()
        {
            return _FillCollections();
        }

        

        #endregion
        
        #region Private Methods

        private string ConvertMDB(bool nurSender)
        {
            string error = string.Empty;
            string appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            Process proc = new Process();
            ProcessStartInfo Startinfo = new ProcessStartInfo(appStartPath + "\\ConvertMDB.exe");

            if (nurSender)
            {
                Startinfo.Arguments = " \"" + this.DBPath + "\" \"" + this.TvdatenXmlFile + "\" SENDER";
            }
            else
            {
                Startinfo.Arguments = " \"" + this.DBPath + "\" \"" + this.TvdatenXmlFile + "\"";
            }
            Startinfo.CreateNoWindow = true;
            Startinfo.UseShellExecute = false;
            Startinfo.RedirectStandardError = true;
            Startinfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo = Startinfo;
            logger.Debug("MDB Convert Process Startet");
            proc.Start();
            error = proc.StandardError.ReadToEnd();
            proc.WaitForExit();
            logger.Debug("MDB Convert Process ist Fertig");
            logger.Error(error);
            return error;
        }

        /// <summary>
        /// Update Clickfinder DB
        /// </summary>
        private void updateClickfinderDB()
        {
            logger.Debug("tvuptodate.exe Process wird gestartet");
            Process proc = new Process();
            ProcessStartInfo Startinfo = new ProcessStartInfo(this.ClickfinderUpdater);
            //ProcessStartInfo Startinfo = new ProcessStartInfo("cmd.exe");
            Startinfo.CreateNoWindow = true;
            Startinfo.WindowStyle = ProcessWindowStyle.Minimized;
            proc.StartInfo = Startinfo;
            proc.Start();
            proc.WaitForExit();
            logger.Debug("tvuptodate.exe Process ist Fertig");
        }

        private string GetDBPath()
        {
            string str = string.Empty;

            RegistryKey Userkey = Registry.Users.OpenSubKey(@"S-1-5-21-2694975618-120438130-3021888964-1000\Software\Classes\VirtualStore\MACHINE\SOFTWARE\Ewe\TVGhost\Gemeinsames");
            RegistryKey HKLMkey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Ewe\TVGhost\Gemeinsames");

            if (Userkey != null)
            {
                str = Userkey.GetValue("DBDatei").ToString();
            }
            else if (HKLMkey != null)
            {
                str = HKLMkey.GetValue("DBDatei").ToString();
            }
            else
            {
                str = Environment.GetEnvironmentVariable("ProgramFiles") + @"\TV Movie\TV Movie ClickFinder\tvdaten.mdb";
            }

            if (!File.Exists(str))
            {
                str = Environment.GetEnvironmentVariable("ProgramFiles(x86)") + @"\TV Movie\TV Movie ClickFinder\tvdaten.mdb";
            }
            if (!File.Exists(str))
            {
                throw new Exception("TV Movie ClickFinder DB Not found!");
            }
            return str;
        }

        private void setVars()
        {
            logger.Debug("Variablen werden gesetzt");
            string Clickfinder_Path = Path.GetDirectoryName(this.DBPath) + @"\";
            this.Logo_Path = Clickfinder_Path + @"Gifs\";
            this.GuideImage_Path = Clickfinder_Path + @"Hyperlinks\";
            this.ClickfinderUpdater = Clickfinder_Path + @"tvuptodate.exe";
            this.Sender_Conf = this.SenderXML_Path + "Sender.xml";
        }

        /// <summary>
        /// Fill the Channel, Programm and Person Collections
        /// </summary>
        /// <returns></returns>
        private bool _FillCollections()
        {

            this.TVprograms = new TVProgrammeCollection();
            this.Persons = new PersonCollection();
            this.KeyWords = new KeywordCollection();
            this.FillSenderCollection(false);

            DateTime consDate = new DateTime(0001, 1, 1);
            DateTime origAirdate = new DateTime(1980, 1, 1);

            string[] Favs = this.GetFavoritesAsArray();

            
            var progs = (from x in this.ds.Sendungen
                         join y in this.ds.SendungenDetails on x.Pos equals y.Pos
                         where Favs.Contains(x.SenderKennung) && x.Beginn >= DateTime.Now.AddHours(-2)
                         orderby x.SenderKennung, x.Beginn ascending
                         select new
                         {
                             x.Pos,
                             x.Beginn,
                             x.Ende,
                             x.SenderKennung,
                             x.SendungID,
                             x.Titel,
                             x.Bewertung,
                             x.Bilddateiname,
                             x.Genre,
                             x.Herstellungsjahr,
                             x.Herstellungsland,
                             x.InhaltID,
                             x.Kategorietext,
                             x.Keywords,
                             x.KurzBeschreibung,
                             x.Kz16zu9,
                             x.KzAudiodescription,
                             x.KzBilddateiHeruntergeladen,
                             x.KzDolby,
                             x.KzDolbyDigital,
                             x.KzDolbySurround,
                             x.KzFilm,
                             x.KzLive,
                             x.KzStereo,
                             x.KzWiederholung,
                             x.Originaltitel,
                             x.Regie,
                             x.FSK,
                             y.Beschreibung,
                             y.Darsteller
                         }).ToArray();
            int count = progs.Count();
            StringBuilder sb = new StringBuilder();
            Person[] pers = null;

            for (int o = 0; o < count; o++)
            {
                int pIndex = 0;
                if (o < count - 1)
                {
                    pIndex = o + 1;
                }
                else
                {
                    pIndex = o;
                }

                var a = progs[o];
                var b = progs[pIndex];

                var getFirst = (from pr in progs where pr.InhaltID == a.InhaltID select pr.Beginn).Min();

                string description = a.Beschreibung;
                string actors = a.Darsteller;

                TVProgramme newProg = new TVProgramme(this.TVprograms.Count + 1, System.Guid.NewGuid().ToString("N"));
                newProg.startTime = a.Beginn.ToUniversalTime();
                if (a.SenderKennung == b.SenderKennung && a.SendungID != b.SendungID)
                {
                    if (a.Beginn == b.Beginn)
                    {
                        continue;
                    }
                    newProg.stopTime = b.Beginn.ToUniversalTime();
                }
                else
                {
                    newProg.stopTime = a.Ende.ToUniversalTime();
                }


                // Channel
                newProg.channel = a.SenderKennung;


                // Title
                newProg.title = a.Titel;//.Replace(@"&", "u.");

                // Peoples
                newProg.ActorRoles = new ArrayList();
                newProg.WriterRoles = new ArrayList();
                newProg.GuestActorRoles = new ArrayList();
                newProg.HostRoles = new ArrayList();
                newProg.ProducerRoles = new ArrayList();
                newProg.DirectorRoles = new ArrayList();

                if (a.KzBilddateiHeruntergeladen && Properties.Settings.Default.LoadImg)
                {
                    GuideImage img = new GuideImage(this.Images.Count + 1, a.Bilddateiname, "file://" + GuideImage_Path + a.Bilddateiname);
                    newProg.guideImageID = img.Id();

                    int hashKeyImage = HelperClass.GetHashCode(img.Url);
                    MCImageInfo pInfo;
                    if (this.MCImages.TryGetValue(hashKeyImage, out pInfo))
                    {
                        img.Uid = pInfo.UID;
                    }
                    else
                    {
                        pInfo = new MCImageInfo(img.Url, img.Uid);
                        this.MCImages.Add(pInfo.HashCode, pInfo);
                    }
                    this.Images.Add(img);
                }
                else
                {
                    newProg.guideImageID = null;
                }

                int hashKeyPerson;
                if (!string.IsNullOrEmpty(a.Regie))
                {
                    Person perso = new Person(this.Persons.Count + 1, a.Regie);
                    perso.Role = Roles.DirectorRole;
                    newProg.DirectorRoles.Add(perso.id());
                    hashKeyPerson = HelperClass.GetHashCode(perso.name);
                    MCPersonInfo pInfo;
                    if (this.MCPersons.TryGetValue(hashKeyPerson, out pInfo))
                    {
                        perso.Uid = pInfo.UID;
                    }
                    else
                    {
                        pInfo = new MCPersonInfo(perso.name, perso.Uid);
                        this.MCPersons.Add(pInfo.HashCode, pInfo);
                    }

                    this.Persons.Add(perso);
                }
                if (actors != string.Empty)
                {
                    pers = HelperClass.getArrayOfPersons(actors);
                    int cnt = pers.Count();
                    for (int i = 0; i < cnt; i++)
                    {
                        Person p = pers[i];
                        if (string.IsNullOrEmpty(p.name))
                        {
                            continue;
                        }
                        p.id_ = this.Persons.Count + 1;
                        switch (p.Role)
                        {
                            case Roles.ActorRole:
                                newProg.ActorRoles.Add(p.id() + ";" + p.Rolle);
                                break;
                            case Roles.GuestActorRole:
                                newProg.GuestActorRoles.Add(p.id());
                                break;
                            case Roles.HostRole:
                                newProg.HostRoles.Add(p.id());
                                break;
                            case Roles.ProducerRole:
                                newProg.ProducerRoles.Add(p.id());
                                break;
                            case Roles.WriterRole:
                                newProg.WriterRoles.Add(p.id());
                                break;
                        }
                        hashKeyPerson = HelperClass.GetHashCode(p.name);
                        MCPersonInfo pInfo;
                        if (this.MCPersons.TryGetValue(hashKeyPerson, out pInfo))
                        {
                            p.Uid = pInfo.UID;
                        }
                        else
                        {
                            pInfo = new MCPersonInfo(p.name, p.Uid);
                            this.MCPersons.Add(pInfo.HashCode, pInfo);
                        }
                        this.Persons.Add(p);
                    }
                }

                //Keywords
                if (a.Keywords != string.Empty)
                {
                    //StringBuilder sb = new StringBuilder();
                    sb.Length = 0;
                    string[] split = a.Keywords.Split(",".ToCharArray());
                    int i = 0;
                    int cnt = split.Count();
                    for (int t = 0; t < cnt; t++)
                    {
                        string p = split[t];
                        var res = (from item in this.KeyWords where item.Word == p select item.Id()).SingleOrDefault();
                        if (res != null)
                        {
                            if (i == 0)
                            {
                                sb.Append(res);
                            }
                            else
                            {
                                sb.Append("," + res);
                            }
                        }
                        else
                        {
                            Keyword key = new Keyword(this.KeyWords.Count + 1, p.Replace(@"&", "u."));
                            this.KeyWords.Add(key);
                            if (i == 0)
                            {
                                sb.Append(key.Id());
                            }
                            else
                            {
                                sb.Append("," + key.Id());
                            }
                        }
                        i++;
                    }
                    newProg.keywords = sb.ToString();
                }

                // Audio Format
                if (a.KzStereo)
                {
                    newProg.audioFormat = audioFormats.Stereo;
                }
                else if (a.KzDolby)
                {
                    newProg.audioFormat = audioFormats.Dolby;
                }
                else if (a.KzDolbyDigital)
                {
                    newProg.audioFormat = audioFormats.DolbyDigital;
                }
                else if (a.KzDolbySurround)
                {
                    newProg.audioFormat = audioFormats.THX;
                }
                else
                {
                    newProg.audioFormat = audioFormats.NotSpecified;
                }

                // isHDTV
                if (a.KurzBeschreibung.Contains("HDTV"))
                {
                    newProg.isHDTV = true;
                }
                else
                {
                    newProg.isHDTV = false;
                }



                // is Movie
                newProg.isMovie = a.KzFilm;

                // is Series
                if (a.Keywords.ToUpper().Contains("serie".ToUpper()) || a.Keywords.ToUpper().Contains("soap".ToUpper()))
                {
                    newProg.isSeries = true;
                }
                else if (newProg.isMovie == false)
                {
                    var countProg = (from xx in progs where xx.Titel == a.Titel && xx.KzWiederholung == false select xx).Count();
                    if (countProg >= 2)
                    {
                        newProg.isSeries = true;
                    }
                }
                else
                {
                    newProg.isSeries = false;
                }

                if ((newProg.isSeries || newProg.isMovie) && a.Originaltitel != string.Empty)
                {
                    newProg.episodeTitle = a.Originaltitel.Trim();
                }

                // Short Description
                if (a.Genre.Trim() != string.Empty)
                {
                    newProg.shortDescription = a.Genre.Trim();
                }

                if (a.Herstellungsland.Trim() != string.Empty)
                {
                    newProg.shortDescription = newProg.shortDescription + " " + a.Herstellungsland.Trim();
                }

                if (a.Herstellungsjahr.Trim() != string.Empty)
                {
                    newProg.shortDescription = newProg.shortDescription + " " + a.Herstellungsjahr.Trim();
                }

                if (newProg.shortDescription != null && Properties.Settings.Default.FSKInfo)
                {
                    newProg.shortDescription = newProg.shortDescription.Trim() + " (FSK" + a.FSK.ToString() + ")";
                }

                // Flags (isNews, isKids, isLive...
                newProg.isNews = a.Kategorietext.ToUpper().Contains("Nachrichten".ToUpper());
                newProg.isSports = a.Kategorietext.ToUpper().Contains("Sport".ToUpper());
                if (a.Kategorietext.ToUpper().Contains("Jugendserie".ToUpper()) || a.Kategorietext.ToUpper().Contains("Kurz-Trickfilm".ToUpper()) || a.Kategorietext.ToUpper().Contains("Zeichentrick".ToUpper()))
                {
                    newProg.isKids = true;
                }
                newProg.isLive = a.KzLive;
                if (newProg.isSports && newProg.isLive)
                {
                    newProg.isLiveSports = true;
                }

                // Description
                description = description.Replace("<br>", " ");
                newProg.description = description.Replace(@"&", "u.");
                if (!string.IsNullOrEmpty(newProg.shortDescription))
                {
                    if (!string.IsNullOrEmpty(newProg.description))
                    {
                        newProg.description = newProg.description + "\n\n" + newProg.shortDescription;
                    }
                    else if (!string.IsNullOrEmpty(newProg.episodeTitle) && string.IsNullOrEmpty(newProg.description))
                    {
                        newProg.description = newProg.episodeTitle;
                    }
                    else
                    {
                        newProg.description = newProg.shortDescription;
                    }
                }

                // Halfstars
                newProg.halfStars = Math.Round(a.Bewertung * 1.3333).ToString();

                // Rating
                newProg.rating = HelperClass.FskToMpaa(a.FSK);


               
                if (newProg.title == "Keine Daten vorhanden.")
                {
                    continue;
                }

                // Repeat
                if (getFirst < a.Beginn)
                {
                    newProg.isRepeat = true;
                    newProg.originalAirdate = origAirdate;
                }
                else if (a.KzWiederholung)
                {
                    newProg.isRepeat = true;

                    if (getFirst == consDate)
                    {
                        newProg.originalAirdate = origAirdate;
                    }
                    else
                    {
                        newProg.originalAirdate = origAirdate;
                    }
                }

                if ((!string.IsNullOrEmpty(newProg.title)) && (!string.IsNullOrEmpty(newProg.description)))
                {
                    int hashKey = HelperClass.GetHashCode(newProg.title, newProg.description);
                    MCProgramInfo value;

                    if (this.MCPrograms.TryGetValue(hashKey, out value))
                    {
                        newProg.uid = value.UID;
                        newProg.originalAirdate = value.FirstScheduleEntry.ToLocalTime();
                    }
                    else
                    {
                        value = new MCProgramInfo(newProg.title, newProg.description, newProg.uid);
                        value.FirstScheduleEntry = newProg.startTime;
                        this.MCPrograms.Add(value.HashCode, value);
                    }
                }

                this.TVprograms.Add(newProg);

                int percentage = (int)(((decimal)o / (decimal)count) * 100);
                this.UiDispatcher.BeginInvoke(this.ProgressDelegate, percentage, count, -3);
            }

            return true;
        }


        private IEnumerable GetFavorites()
        {
            var sender = (from x in this.ds.Sender
                          where x.Favorit == true
                          select x.Bezeichnung).AsEnumerable();
            return sender;
        }

        private string[] GetFavoritesAsArray()
        {
            var sender = (from x in this.ds.Sender
                          where x.Favorit == true
                          select x.SenderKennung).ToArray<string>();
            return sender;
        }

        
        private void FillSenderCollection(bool Conf)
        {
            bool loadlogo = Properties.Settings.Default.LoadLogo;
            
            if (Conf)
            {
                var sender = from x in this.ds.Sender
                             where x.Favorit == true
                             select x;
                foreach (var a in sender)
                {
                    TVChannel newChannel = new TVChannel(this.TVChannels.Count + 1, a.Bezeichnung.ToUpper(), a.SenderKennung.ToLower());
                    GuideImage img = null;
                    if (loadlogo)
                    {
                        string _img = Logo_Path + a.Zeichen;
                        string[] split = _img.Split('.');
                        img = new GuideImage(this.Images.Count + 1, a.Bezeichnung, "file://" + split[0] + "_gr.gif");
                        newChannel.logoUrlID = img.Id();
                        newChannel.logoUrl = split[0] + "_gr.gif";
                    }
                    else
                    {
                        int i = -1;
                        newChannel.logoUrlID = i.ToString();
                        newChannel.logoUrl = "NONE";
                    }
                    if (Properties.Settings.Default.AutoHD)
                    {
                        if (newChannel.name_.Contains("HD") || newChannel.name_.Contains("HDTV"))
                        {
                            newChannel.isHDTV = true;
                        }
                    }

                    this.TVChannels.Add(newChannel);

                    if (img != null)
                    {
                        if (this.MCImages != null)
                        {
                            int hashKeyImage = HelperClass.GetHashCode(img.Url);
                            MCImageInfo pInfo;
                            if (this.MCImages.TryGetValue(hashKeyImage, out pInfo))
                            {
                                img.Uid = pInfo.UID;
                            }
                            else
                            {
                                pInfo = new MCImageInfo(img.Url, img.Uid);
                                this.MCImages.Add(pInfo.HashCode, pInfo);
                            }
                        }
                        this.Images.Add(img);
                    }
                }
            }
            else
            {
                if (File.Exists(this.Sender_Conf))
                {
                    this.senderXML = new SenderDataset();
                    senderXML.ReadXml(this.Sender_Conf);
                }
                else
                {
                    throw new ApplicationException("Konfigurations Datei " + this.Sender_Conf + " nicht vorhanden!");
                }

                var sender = from x in this.senderXML.Source
                             where x.Active == true
                             select x;

                foreach (var a in sender)
                {
                    TVChannel newChannel = new TVChannel(TVChannels.Count + 1, a.CF_Sender.ToUpper(), a.CF_Searchstring.ToLower());
                    GuideImage img = null;

                    if (loadlogo)
                    {
                        img = new GuideImage(this.Images.Count + 1, a.CF_Sender, "file://" + a.url);
                        newChannel.logoUrlID = img.Id();
                        newChannel.logoUrl = a.url;
                    }
                    else
                    {
                        int i = -1;
                        newChannel.logoUrlID = i.ToString();
                        newChannel.logoUrl = "NONE";
                    }
                    newChannel.isHDTV = a.isHD;
                    newChannel.MatchName = a.MatchName;
                    newChannel.MCSender = a.MC_Sender;

                    this.TVChannels.Add(newChannel);
                    if (img != null)
                    {
                        if (this.MCImages != null)
                        {
                            int hashKeyImage = HelperClass.GetHashCode(img.Url);
                            MCImageInfo pInfo;
                            if (this.MCImages.TryGetValue(hashKeyImage, out pInfo))
                            {
                                img.Uid = pInfo.UID;
                            }
                            else
                            {
                                pInfo = new MCImageInfo(img.Url, img.Uid);
                                this.MCImages.Add(pInfo.HashCode, pInfo);
                            }
                        }
                        this.Images.Add(img);
                    }
                }
            }
        }

        #endregion

    }
}
